package software.agileCourse2013.KillerGame.web.MessageBound;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.json.JSONObject;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

import software.agileCourse2013.KillerGame.biz.Command.TemplateCommand;
import software.agileCourse2013.KillerGame.service.models.UserModel;
import software.agileCourse2013.KillerGame.utils.CommandDispatcherUtils;
import software.agileCourse2013.KillerGame.utils.SpringContextutil;

public class ChatMessageInbound extends MessageInbound {
	private static final Map<Integer, UserModel> map = new ConcurrentHashMap<Integer, UserModel>();
	private UserModel user;
	private CommandDispatcherUtils commandDispatcher;
	
	public ChatMessageInbound() {
		if (commandDispatcher == null) {
			commandDispatcher = (CommandDispatcherUtils) SpringContextutil.getBean("commandDispatcher");
		}
	}
	
	public ChatMessageInbound(UserModel user) {
		this.user = user;
		if (commandDispatcher == null) {
			commandDispatcher = (CommandDispatcherUtils) SpringContextutil.getBean("commandDispatcher");
		}
	}
	
	@Override
    protected void onOpen(WsOutbound outbound) {
		user.setOutBound(outbound);
      map.put(outbound.hashCode(), user);
      super.onOpen(outbound);
    }

    @Override
    protected void onClose(int status) {
      map.remove(getWsOutbound().hashCode());
      super.onClose(status);
    }

    @Override
    protected void onBinaryMessage(ByteBuffer buffer) throws IOException {

    }

    @Override
    protected void onTextMessage(CharBuffer buffer) throws IOException {
      String msg = buffer.toString();
      JSONObject report = JSONObject.fromObject(msg);
      TemplateCommand command = commandDispatcher.getCommandByKey(report.getString("command"));
      command.execute(msg,user,map);
    }

}
